<!-- 图像操作区 -->
<template>
  <div class="lsh-image-editor" ref="boxRef">
    <button @click="">+</button>
    <button @click="">-</button>
    <button @click="hanInitSize">恢复</button>
    <button @click="isAdd = !isAdd">{{isAdd?'关闭':'开启'}}</button>
    <div id="stage">

    </div>
  </div>
</template>

<script setup lang='ts'>
import { ref, onMounted, reactive } from 'vue';
import Konva from 'konva';
import {doRectanglesIntersect,getBbox} from '../../util'
let stage: Konva.Stage;
let bgLayer: Konva.Layer;
let centerLayer: Konva.Layer;
let topLayer: Konva.Layer;
let newRect: Konva.Rect | null;
let tr: Konva.Transformer;
let mousedown: boolean = false;
let scaleBy = 0.9;
let scaleObj = {
  scaleX: 1,
  scaleY: 1,
};
const isAdd = ref(true || false);
const boxRef = ref();
const list = Array.from(new Array(200));
const hanLoadeImages = () => {
  bgLayer = new Konva.Layer({
    listening: false,
  });
  stage.add(bgLayer);
  Konva.Image.fromURL('src/assets/image/test.png', function (darthNode) {
    const { width, height } = darthNode.attrs.image;
    scaleObj.scaleX = stage.width() / width;
    scaleObj.scaleY = stage.height() / height;
    darthNode.setAttrs({
      x: 0,
      y: 0,
      // ...scaleObj,
    });
    bgLayer.add(darthNode);
    bgLayer.batchDraw();
  });
}
const initCanvas = () => {
  stage = new Konva.Stage({
    container: 'stage',
    width: boxRef.value.clientWidth,
    height: boxRef.value.clientHeight,
    scale: { x: 1, y: 1 },
  });
  hanLoadeImages();
  centerLayer = new Konva.Layer();
  stage.add(centerLayer);
  centerLayer.draw();
  topLayer = new Konva.Layer();
  stage.add(topLayer);
  topLayer.draw();
  bindEvent();
}
const bindEvent = () => {
  stage.on('mousedown', (e) => {
    if (newRect) return;
    newRect = new Konva.Rect({
      x: e.evt.offsetX,
      y: e.evt.offsetY,
      width: 0,
      height: 0,
      stroke: "rgba(249, 4, 33, 1)",
      fill: "rgba(255, 164, 160, 0.4)",
      draggable: true,
      name: 'rect',
      strokeScaleEnabled: false,
    })
    // newRect.on('mouseenter', (e) => {
    //   e.target.setAttrs({
    //     fill: 'rgba(255,255,0,0.5)',
    //   })
    //   stage.container().style.cursor = 'pointer';
    //   centerLayer.batchDraw();
    // })
    // newRect.on('mouseleave', (e) => {
    //   e.target.setAttrs({
    //     fill: 'rgba(255, 164, 160, 0.4)'
    //   })
    //   stage.container().style.cursor = 'default';
    //   centerLayer.batchDraw();
    // })
    topLayer.add(newRect);
    topLayer.batchDraw();
    mousedown = true;
  })
  stage.on('mousemove', (e) => {
    if (!mousedown || !newRect) return;
    newRect.setAttrs({
      width: e.evt.movementX + newRect.width(),
      height: e.evt.movementY + newRect.height(),
    })
    topLayer.batchDraw();
    if(!isAdd.value){
      const selectBox = getBbox({
        top:newRect.x(),
        left:newRect.y(),
        width: newRect.width(),
        height:newRect.height(),
        scaleX:stage.scaleX(),
        scaleY:stage.scaleY(),
        rectScaleX:newRect.scaleX(),
        rectScaleY:newRect.scaleY(),
      },{left:0,top:0}) 
      centerLayer.children.forEach((item)=>{
        const bbox = getBbox({
          top:item.x(),
          left:item.y(),
          width: item.width(),
          height:item.height(),
          scaleX:stage.scaleX(),
          scaleY:stage.scaleY(),
          rectScaleX:item.scaleX(),
          rectScaleY:item.scaleY(),
        },{left:0,top:0})
        if(!doRectanglesIntersect(selectBox,bbox))return item.setAttr("fill","red");
        // console.log("相交",selectBox,bbox)
        item.setAttr("fill","blue");
      })
      centerLayer.draw();
    }
  })
  stage.on('mouseup', (e) => {
    if (!newRect) return
    if (isAdd.value) {
      centerLayer.add(newRect.clone());
      centerLayer.batchDraw();
    }
    newRect.remove();
    newRect = null;
  })
  stage.on('click tap', function (e) {
    console.log(e)
    // if click on empty area - remove all transformers
    if (e.target === stage) {
      tr?.destroy?.();
      topLayer.draw();
      return;
    }
    console.log('点击1')

    // do nothing if clicked NOT on our rectangles
    console.log(e.target.name())
    if (!e.target.hasName('rect')) {
      return;
    }
    // remove old transformers
    // TODO: we can skip it if current rect is already selected
    tr?.destroy?.();
    console.log('点击2')
    // create new transformer
    tr = new Konva.Transformer({
      anchorStroke: 'red',
      anchorFill: 'rgba(255, 255, 255, 1)',
      anchorSize: 9,
      borderStroke: 'rgba(249, 4, 33, 1)',
      rotateEnabled: false,
      // enabledAnchors: ['top-left', 'top-right', 'bottom-left', 'bottom-right'],
      anchorCornerRadius: 10,
      anchorStrokeWidth:3,
      ignoreStroke: true,
      padding:0,
      // borderDash: [3, 3]
    } as Konva.TransformerConfig);
    centerLayer.add(tr);
    tr.attachTo(e.target);
    centerLayer.draw();
  });
  stage.on('keypress wheel', e => {
    if (!e.evt.ctrlKey) return;
    e.evt.preventDefault();
    if (!stage) return;
    const oldScale = stage.scaleX();
    const mousePointTo = {
      x: stage.getPointerPosition().x / oldScale - stage.x() / oldScale,
      y: stage.getPointerPosition().y / oldScale - stage.y() / oldScale
    };
    const newScale =
      e.evt.deltaY > 0 ? oldScale * scaleBy : oldScale / scaleBy;
    stage.scale({ x: newScale, y: newScale });

    const newPos = {
      x:
        -(mousePointTo.x - stage.getPointerPosition().x / newScale) *
        newScale,
      y:
        -(mousePointTo.y - stage.getPointerPosition().y / newScale) *
        newScale
    };
    stage.position(newPos);
    stage.batchDraw();
  });
}
onMounted(() => {
  initCanvas();
})
const hanInitSize = () => {
  stage.x(0);
  stage.y(0);
  stage.scale({
    x: 1,
    y: 1,
  })
  stage.batchDraw();
}
</script>
<style scoped lang='less' >
@import url('./index.less');
</style>